package com.michaelbulava.TFS.tasks.connect;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.michaelbulava.TFS.Messages;
import com.michaelbulava.TFS.tasks.BackgroundableTask;
import com.michaelbulava.TFS.vcs.utils.TFSFileUtil;
import com.michaelbulava.TFS.vcs.utils.TFSProgressUtil;
import com.microsoft.tfs.core.clients.versioncontrol.workspacecache.WorkspaceInfo;
import org.jetbrains.annotations.NotNull;

import java.text.MessageFormat;

/**
 * Created by MichaelA on 9/21/2015.
 */
public class CheckModuleForWorkspace extends BackgroundableTask {
    private final Module myModule;

    private WorkspaceInfo workspaceInfo;
    private WorkspaceCheckCompletedListener listener;

    public interface WorkspaceCheckCompletedListener{
        void WorkspaceCheckComplete(WorkspaceInfo workspaceInfo);
    }

    public CheckModuleForWorkspace(@NotNull Module module) {
        super(module.getProject(), MessageFormat.format(Messages.getString("CheckModuleForWorkspace.Title_FORMAT"),
                new Object[]{ module.getName() }), false);
        myModule = module;
    }

    public void setWorkspaceCheckCompletedListener(WorkspaceCheckCompletedListener listener){
        this.listener = listener;
    }

    @Override
    protected boolean runInBackground() {
        return true;
    }

    @Override
    public void run(ProgressIndicator indicator) {
        TFSProgressUtil.setProgressText2(indicator, "Checking if module folder belongs to know workspaces...");
        workspaceInfo = TFSFileUtil.findWorkspace(myModule.getModuleFile(), true, myProject);
    }

    public void onSuccess() {
        if (listener != null)
            listener.WorkspaceCheckComplete(this.workspaceInfo);
    }

    public void onCancel() {
        if (listener != null)
            listener.WorkspaceCheckComplete(null);
    }

    public WorkspaceInfo getWorkspaceInfo(){
        return this.workspaceInfo;
    }

}
